define(function(require, exports) {
	var $ = require('jquery');
	var util = require('util');
	var pubjs = require('pubjs');
	var view  = require('@base/view');

	// 活动编辑，黑白名单
	var White = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				 max_list: 10
				 // 白名单为1，黑名单为2
				,WhiteBlackType: 1
				,gridConfig: {
					 default_sort: false
					,exclude_cols: ['AdxId']
					,auto_load: false
					,hasSearch: false
					,hasPager: false
					,hasTab: false
					,hasExport: false
					,hasAmount: false
					,opClick: true
					,cols: [
						 {name:"_id", text:LANG('ID'),type:'fixed',sort:true,align:'center', width:60, render: 'renderId'}
						,{name: 'Name', type:'index',render:'renderName',width:200}
						,{name: 'AdxId', text:LANG('渠道'), format:'formatChannel', align:'center'}
						// ,{name: 'PageClass', text:LANG('优酷分类数'), render:'renderYoukuCount',align:'center'}
						,{name: 'SiteClass', text:LANG('域名分类数'), render:'renderSiteClass',align:'center'}
						,{name: 'Domain', text:LANG('域名数量'), render:'renderCount',align:'center'}
						,{name: 'Size', text:LANG('尺寸数量'), render:'renderCount',align:'center'}
						,{name: 'PositionIds', text:LANG('广告位数量'), render:'renderCount',align:'center'}
						,{name: 'Remark', text:LANG('备注'), render:'renderRemark',align:'center', width: 250}
						,{name: 'operation', type:'op', render:'renderOperation', width: 100}
					]
				}
				,view_model: {
					// 导入按钮点击事件
					evImportBtnClick: this.eventImportBtnClick
					// 新建按钮点击事件
					,evAddBtnClick: this.eventAddBtnClick
				}
			});
			this.$value = [];
			this.$exchangeId = 0;
			this.$channels = pubjs.config('channelMap');
			this.$youku = pubjs.config('exchange_group/youku');

			this.Super('init', arguments);
		}
		,afterBuild: function() {
			//var WhiteBlackType = this.getConfig('WhiteBlackType');

			this.append([
				'<div class="button-wrap mb15">',
					'<button ms-click="evImportBtnClick" class="btn btn-default mr15">' + LANG('导入公用分组') + '</button>',
					'<button ms-click="evAddBtnClick" class="btn btn-default">' + LANG('新建分组') + '</button>',
				'</div>',
				'<div pub-name="grid" pub-mod="@base/grid.base" class="grid-wrap" />'
			].join(''));

			// // 导入窗口
			// this.createAsync('import', 'adsGroup/popwin/import.base', {
			// 	WhiteBlackType: WhiteBlackType
			// });

			// // 编辑窗口
			// this.createAsync('edit', 'adsGroup/action/edit.popwin', {
			// 	WhiteBlackType: WhiteBlackType
			// });

			this.buildFromTemplate({
				grid: this.getConfig('gridConfig')
			});

		}
		,formatChannel: function(val){
			return this.$channels[val] || LANG('未知渠道');
		}
		,renderId: function(i, val, data,con){
			return val || data.Id || '-';
		}
		,renderName: function(i, val, data,con){
			val = val || LANG('默认分组');
			return $('<span class="M-tableListWidthLimit"/>')
				.attr({'title':val})
				.text(val).width(con.width);
		}
		,renderRemark: function(i, val, data, con) {
			val = val || '-';
			return $('<span class="M-tableListWidthLimit"/>')
				.attr({'title':val})
				.text(val).width(con.width);
		}
		,renderYoukuCount: function(idx, val, row, col){
			if (row.AdxId && !util.exist(this.$youku, row.AdxId)){
				return '-';
			}
			return val && val.length || LANG('全部');
		}
		,renderSiteClass: function(idx, val, row, col){
			if (!val){
				// 兼容广告分组
				val = row.Spots && row.Spots[col.name];
				if(util.exist(this.$youku, row.AdxId)){
					val = row.Spots.PageClass;
				}
			}
			return val && val.length || LANG('全部');
		}
		,renderCount: function(idx, val, row, col){
			if (!val){
				// 兼容广告分组
				val = row.Spots && row.Spots[col.name];
			}
			return val && val.length || LANG('全部');
		}
		,renderOperation: function(idx, val, row) {
			var ops = [
				'<a href="#" data-op="edit">'+LANG("编辑")+'</a>',
				'<a href="#" data-op="remove">'+LANG("删除")+'</a>'
			];

			return ops.join(' | ');
		}
		,reset: function() {
			this.$value = [];
			this.$exchangeId = 0;
			this.$.grid.setData([]);
			return this;
		}
		,getValue: function() {
			return (this.$value ? this.$value.slice() : []);
		}
		,setValue: function(value) {
			this.$value = value;
			this.$.grid.setData(value);
			return this;
		}
		,onExchangeIdChange: function(ev){
			var cid = ev.param;
			var cols;
			var group = pubjs.config('exchange_group');
			switch (true){
				case util.exist(group.tanx, cid):
				case util.exist(group.baidu, cid):
				case util.exist(group.yigao, cid):
					// Tanx, 百度, 亿告渠道分类
					cols = ['Name', 'SiteClass', 'Domain', 'Size', 'PositionIds', 'Remark'];
					break;
				case util.exist(group.google, cid):
					// double_click有分类，没有域名 (暂时没有分类)
					cols = ['Name', /*'SiteClass', */'Size', 'PositionIds', 'Remark'];
					break;
				case util.exist(group.youku, cid):
					// 优酷没有域名和网站分类
					cols = ['Name', 'PageClass', 'Size', 'PositionIds', 'Remark'];
					break;
				default:
					cols = ['Name', 'Size', 'PositionIds', 'Remark']
					break;
			}
			this.$exchangeId = cid;
			this.$.grid.showColumn(cols);
			return this;
		}
		// 创建广告位分组
		,createGroup: function() {
			var self = this;
			var limit = this.getConfig('max_list');
			if (self.$value.length >= limit){
				pubjs.alert(LANG('已达到列表的最大数量'));
			}else {
				//传入分组类型和广告渠道参数
				var data = {
					AdxId:self.$exchangeId,
					WhiteBlackType:this.getConfig('WhiteBlackType')
				}
				self.$.edit.reset().setEdit().setData(data).show();
				// self.$.edit.reset().show();
			}
			return self;
		}
		// 编辑广告位分组
		,editGroup: function(idx) {
			var self = this;
			var data = self.$value[idx];
			data.AdxId = data.AdxId || self.$exchangeId;
			pubjs.loading.show();
			self.checkEditBox(function(){
				pubjs.loading.hide();
				self.$.edit.reset().setEdit().setData(data).show();
			});
			return self;
		}
		// 移除广告位分组
		,removeGroup: function(idx) {
			var self = this;
			var list = self.$value;
			pubjs.confirm(LANG('要删除广告位分组: %1 吗?', list[idx].Name || LANG('默认分组')), function(isOk){
				if(isOk){
					list.splice(idx, 1);
					self.setValue(list);
				}
			});
			return self;
		}
		// 导入广告位分组
		,importGroup: function() {
			var self = this;
			self.$.import.reset().setParam({
				ChannelId: self.$exchangeId,
				WhiteBlackType: self.getConfig('WhiteBlackType')
			}).load().setValue(self.$value).show();
			return self;
		}
		,onImportGroup: function(ev){
			var self = this;
			var grid = self.$.grid,
				list = self.$value,
				max = self.getConfig('max_list');
			util.each(ev.param, function(item){
				if (list.length >= max){
					pubjs.alert(LANG('已达到列表的最大数量!'));
					return false;
				}
				if (util.index(list, item._id, '_id') === null) {
					list.push(item);
				}
			});

			grid.setData(list);
			return false;
		}
		// 编辑广告位分组保存
		,onEditAdsGroupDone: function(ev) {
			var data = ev.param;
			var pop = ev.from;
			var empty = true;
			util.each(data.Spots, function(val){
				if (util.isArray(val) && val.length){
					empty = false;
				}
			});
			data.Name = util.trim(data.Name);
			var err = [];
			if (!data.Name){
				err.push(LANG('分组名称不能为空'));
			}
			var re = /黑名单/ig;
			if(re.test(data.Name) && data.WhiteBlackType == 1){
				err.push(LANG('分组名称带有"黑名单"，请修改。当前分组类型为白名单'));
			}
			var re2 = /白名单/ig;
			if(re2.test(data.Name) && data.WhiteBlackType == 2){
				err.push(LANG('分组名称带有"白名单"，请修改。当前分组类型为黑名单'));
			}
			if (data.WhiteBlackType != this.getConfig('WhiteBlackType')) {
				err.push(LANG("黑白名单类型错误"));
			}
			if (data.AdxId != this.$exchangeId) {
				err.push(LANG("渠道类型选择错误"));
			}
			if (empty){
				err.push('请选择一个分组过滤条件');
			}
			if (err.length){
				pubjs.alert(LANG('分组资料存在问题: ') + err.join('、'));
			} else {
				var index;
				var list = this.$value;
				var grid = this.$.grid;

				if (data._id) {
					// 如果有id，则判断id是否存在
					index = util.index(list, data._id, '_id');
				} else if (data._frontend_id) {
					// 不存在id时，判断前端临时id是否存在
					index = util.index(list, data._frontend_id, '_frontend_id');
				} else {
					// 不存在前端临时id则添加一个前端临时id
					data._frontend_id = +new Date();
				}

				if (util.isNumber(index)) {
					// 查找到则继承(只可合并一层，Spots内的数组合并不会覆盖)
					list[index] = util.clone(data);
					//util.extend(1, list[index], data);
				} else {
					// 否则追加
					list.push(data);
				}

				grid.setData(list);
				pop.hide();
			}
			return false;
		}
		,onListOpClick: function(ev){
			var self = this
			var param = ev.param;

			if (ev.source === self.$.grid){
				switch (param.op){
					case 'edit':
						self.editGroup(param.index);
					break;
					case 'remove':
						self.removeGroup(param.index);
					break;
				}
			}

			return false;
		}
		,eventImportBtnClick: function(ev) {
			var self = this;
			pubjs.loading.show();
			self.checkImportBox(function(){
				pubjs.loading.hide();
				self.importGroup();
			});
		}
		,eventAddBtnClick: function(ev) {
			var self = this;
			pubjs.loading.show();
			self.checkEditBox(function(){
				pubjs.loading.hide();
				self.createGroup();
			});
		}
		,checkEditBox: function(callback){
			var WhiteBlackType = this.getConfig('WhiteBlackType');
			this.checkModule('edit', 'adsGroup/action/edit.popwin', {
				'WhiteBlackType': WhiteBlackType
			}, callback);
		}
		,checkImportBox: function(callback){
			var WhiteBlackType = this.getConfig('WhiteBlackType');
			this.checkModule('import', 'adsGroup/popwin/import.base', {
				'WhiteBlackType': WhiteBlackType
			}, callback);
		}
		,checkModule: function(mod, path, param, callback){
			if(util.isFunc(param)){
				callback = param;
				param = {};
			}
			if(!this.$[mod] && path){
				param = param || {};
				if(util.isFunc(callback)){
					this.createAsync(mod, path, param, callback);
				}else{
					this.createAsync(mod, path, param);
				}
			}else{
				if(util.isFunc(callback)){
					callback();
				}
			}
		}

	});

	exports.white = White;

	var Black = White.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				WhiteBlackType: 2
			});

			this.Super('init', arguments);
		}
	});
	exports.black = Black;
});